package com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.repository;

import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.StringUtils;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.exception.TaskVariableSetException;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.object.ObjectMetaQueryVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.task.TaskVariableSetRequestVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.task.TaskVariableSetResponseVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.TaskVariableRepository;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author lich
 * @date 2021/11/17
 */
@Service
public class TaskVariableRepositoryImpl implements TaskVariableRepository {

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Override
    public TaskVariableSetResponseVo setTaskVariable(TaskVariableSetRequestVo requestVo) {
        validateRequestVo(requestVo);

        TaskVariableSetResponseVo responseVo = new TaskVariableSetResponseVo();
        if (StringUtils.isNotEmpty(requestVo.getWorkItemId())) {
            Task task = taskService.createTaskQuery()
                    .processInstanceId(requestVo.getProcessInstanceId())
                    .taskId(requestVo.getWorkItemId())
                    .singleResult();
            if (task == null) {
                throw new TaskVariableSetException("没有找到该任务，任务信息可能不对，或许任务已经被完成");
            }


            boolean variableExist = taskService.hasVariable(requestVo.getWorkItemId(), requestVo.getKey());
            responseVo.setVariableExistBefore(variableExist);

            Object oldValue = taskService.getVariable(requestVo.getWorkItemId(), requestVo.getKey());
            responseVo.setOldValue(oldValue);

            taskService.setVariable(requestVo.getWorkItemId(), requestVo.getKey(), requestVo.getValue());
            Object newValue = taskService.getVariable(requestVo.getWorkItemId(), requestVo.getKey());

            responseVo.setNewValue(newValue);
            responseVo.setWorkItemId(requestVo.getWorkItemId());
            responseVo.setProcessInstanceId(requestVo.getProcessInstanceId());
        }else {
            // 任务id为空时，默认根据流程实例id更新流程变量
            boolean variableExist = runtimeService.hasVariable(requestVo.getProcessInstanceId(), requestVo.getKey());
            responseVo.setVariableExistBefore(variableExist);

            Object oldValue = runtimeService.getVariable(requestVo.getProcessInstanceId(), requestVo.getKey());
            responseVo.setOldValue(oldValue);

            runtimeService.setVariable(requestVo.getProcessInstanceId(), requestVo.getKey(), requestVo.getValue());
            Object newValue = runtimeService.getVariable(requestVo.getProcessInstanceId(), requestVo.getKey());

            responseVo.setNewValue(newValue);
            responseVo.setWorkItemId(requestVo.getWorkItemId());
            responseVo.setProcessInstanceId(requestVo.getProcessInstanceId());
        }

        return responseVo;
    }

    private void validateRequestVo(TaskVariableSetRequestVo requestVo) {
        if (requestVo.getKey() == null) {
            throw new TaskVariableSetException("缺乏需要设置的key");
        }

        if (requestVo.getValue() == null) {
            throw new TaskVariableSetException("value的值为null或者未设置，暂时不允许设置一个null值");
        }

        if (requestVo.getProcessInstanceId() == null) {
            throw new TaskVariableSetException("缺乏流程实例id（processInstanceId）");
        }

//        if (requestVo.getWorkItemId() == null) {
//            throw new TaskVariableSetException("缺乏任务实例id（workItemId）");
//        }

    }
}
